package com.maolong.spring.context.support;

import com.maolong.spring.beans.BeansException;
import com.maolong.spring.beans.factory.config.BeanFactoryPostProcessor;
import com.maolong.spring.beans.factory.config.BeanPostProcessor;
import com.maolong.spring.beans.factory.support.ConfigurableListableBeanFactory;
import com.maolong.spring.context.ConfigurableApplicationContext;
import com.maolong.spring.core.io.DefaultResourceLoader;

import java.util.Map;

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
    @Override
    public void refresh() {
        //1.创建beanFactory,并加载BeanDefinition
        refreshBeanFactory();

        //2.获取beanFactory(maolong-->这个ConfigurableListableBeanFactory是最底层了)
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();

        //3.在Bean实例化之前,执行invokeBeanFactoryPostProcessors方法
        invokeBeanFactoryPostProcessors(beanFactory);

        // 4. BeanPostProcessor需要提前于其他 Bean 对象实例化之前执行注册操作
        registerBeanPostProcessors(beanFactory);

        // 5. 提前实例化单例Bean对象
         beanFactory.preInstantiateSingletons();
    }


    protected abstract void refreshBeanFactory();

    protected abstract ConfigurableListableBeanFactory getBeanFactory();

    private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanPostProcessor> beansOfType = beanFactory.getBeansOfType(BeanPostProcessor.class);
        for (BeanPostProcessor beanPostProcessor : beansOfType.values()) {
            beanFactory.addBeanPostProcessor(beanPostProcessor);
        }
    }

    private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanFactoryPostProcessor> beansOfType = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class);
         for (BeanFactoryPostProcessor beanFactoryPostProcessor : beansOfType.values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
    }
    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        return getBeanFactory().getBeansOfType(type);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return getBeanFactory().getBean(name);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return getBeanFactory().getBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return getBeanFactory().getBean(name, requiredType);
    }




}
